import api from "@/api";
export default {
  namespaced: true, //模块
  state() {
    return {
      commoditycategory: {},
    };
  },
  getters: {
    productCategoryMap(state) {
      return state.commoditycategory.results.reduce((prev, current) => {
        prev[current.id] = current;
        return prev;
      }, {}); // {商品类别的id: 商品类别完整内容, 2: {}}
    },
    getChildrenList(state) {
      return (id) => {
        return state.commoditycategory.results.filter(
          (category) => category.parent == id
        );
      };
    },
  },
  mutations: {
    getCategory(state, payload) {
      state.commoditycategory = payload;
    },
    createCategory(state, payload) {
      state.commoditycategory.results.push(payload);
    },
    editcategory(state, payload) {
      let index = state.commoditycategory.results.findIndex(
        (category) => category.id == payload.id
      );
      state.commoditycategory.results.splice(index, 1, payload);
    },
    delete(state, payload) {
      let index = state.commoditycategory.results.findIndex(
        (category) => category.id == payload.id
      );
      state.commoditycategory.results.splice(index, 1);
    },
  },
  actions: {
    async getCategory({ commit }) {
      //发起请求并将数据传递给getMenuTree中的payload
      try {
        let { data } = await api.category();
        commit("getCategory", data);
      } catch (err) {
        console.log(err);
      }
    },
    //添加商品类别的方法
    async createCategory({ commit }, payload) {
      try {
        let { data } = await api.createcategory(payload);
        console.log(data);
        commit("createCategory", data);
        // return Promise.resolve(data);
        return data; // == Promise.resolve(data);
      } catch (err) {
        return Promise.resolve(err);
      }
    },
    async editcategory({ commit }, payload) {
      try {
        let { data } = await api.editcategory(payload);
        console.log(data);
        commit("editcategory", data);
        // return Promise.resolve(data);
        return data; // == Promise.resolve(data);
      } catch (err) {
        return Promise.resolve(err);
      }
    },
    async delete({ commit }, payload) {
      try {
        let { data } = await api.deletecategory(payload);
        console.log(data);
        commit("delete", data);
        // return Promise.resolve(data);
        return data; // == Promise.resolve(data);
      } catch (err) {
        return Promise.resolve(err);
      }
    },
  },
};
